// websocket实例
var wSocket ;
// URL地址
var wsURL = "ws://192.168.1.171:8080/Socket_Demo1/ws/"
// 防止重连标记
var lockReconnect = false;

// 连接
function connect() {
	if(typeof(WebSocket) == "undefined") {
		alert("您的浏览器不支持WebSocket");
		return;
	}
	
	// 创建连接
	//wSocket = new WebSocket(url);
	var user = document.getElementById("username").value;
	wSocket = new WebSocket(wsURL + user);
	// 连接以后监听事件
	initEventHandle();
}

// 发送消息
function sendMessage() {
	var doc = document.getElementById("message");
	if (doc.value == "") {
		return;
	}
	wSocket.send(doc.value);
	doc.value = null;
}

// 关闭Socket
function closeSocket() {
	lockReconnect = false;
	wSocket.close();
}

// 监听事件处理
function initEventHandle() {
	wSocket.onclose = function () {
		//alert("连接关闭正在重连");
		var stateText = document.getElementById("state");
		stateText.innerHTML = "离线，正在重新连接";
		stateText.style.color = "red";
		// 重连
        reconnect(wsURL);
    };
    wSocket.onerror = function () {
    	//alert("连接出错正在重连");
		var stateText = document.getElementById("state");
		stateText.innerHTML = "error，正在重新连接";
		stateText.style.color = "red";
    	//  重连
        reconnect(wsURL);
    };
    wSocket.onopen = function () {
    	//alert("已打开连接");
		var stateText = document.getElementById("state");
		stateText.innerHTML = "在线";
		stateText.style.color = "green";
        //心跳检测重置
        heartCheck.reset().start();
    };
    wSocket.onmessage = function (msg) {
    	// 心跳包不显示，开发时心跳包应设计为json格式字符串
    	if (msg.data != "HeartBeat") {
        	document.getElementById("receive").innerHTML = msg.data;
    	}
        //如果获取到消息，心跳检测重置
        //拿到任何消息都说明当前连接是正常的
        heartCheck.reset().start();
    }
}
    
function reconnect() {
    if(lockReconnect) return;
    lockReconnect = true;
    //没连接上会一直重连，设置延迟避免请求过多
    setTimeout(function () {
    	connect();
        lockReconnect = false;
    }, 3000);
}
    
//心跳检测
var heartCheck = {
    timeout: 60000,//60秒
    timeoutObj: null,
    serverTimeoutObj: null,
    reset: function(){
        clearTimeout(this.timeoutObj);
        clearTimeout(this.serverTimeoutObj);
        return this;
    },
    start: function(){
        var self = this;
        this.timeoutObj = setTimeout(function(){
            //这里发送一个心跳，后端收到后，返回一个心跳消息，
            //onmessage拿到返回的心跳就说明连接正常
        	wSocket.send("HeartBeat");
            //如果超过一定时间还没重置，说明后端主动断开了
            self.serverTimeoutObj = setTimeout(function(){
            	//如果onclose会执行reconnect，我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
            	wSocket.close();
            }, self.timeout)
        }, this.timeout)
    }
}

// 需要输入用户名以后连接
//connect();




